<template>
  <div class="flex flex-col h-full overflow-hidden">
    <app-header/>

    <main>
      <div class="page-header">
        <h2 class="page-title">{{ isEditMode ? '编辑PLC地址' : '添加PLC地址' }}</h2>
        <p class="page-description">
          {{ isEditMode ? '修改现有PLC地址的配置' : '创建新的PLC地址配置' }}
        </p>
      </div>

      <form class="address-form" @submit.prevent="saveAddress">
        <div class="form-row two-columns">
          <div class="form-field" :class="{ 'has-error': validationErrors.address }">
            <label for="address">PLC地址 <span class="required-mark">*</span></label>
            <input
                type="text"
                id="address"
                v-model="form.address"
                placeholder="例如: MW100, D200"
                :disabled="isLoading"
                @blur="validateAddress"
                required
            />
            <p v-if="validationErrors.address" class="field-error">{{ validationErrors.address }}</p>
            <p v-else class="field-hint">输入有效的PLC地址格式，如MW100</p>
          </div>

          <div class="form-field" :class="{ 'has-error': validationErrors.propertyName }">
            <label for="propertyName">属性名称 <span class="required-mark">*</span></label>
            <input
                type="text"
                id="propertyName"
                v-model="form.propertyName"
                placeholder="输入地址属性名称"
                :disabled="isLoading"
                @blur="validatePropertyName"
                required
            />
            <p v-if="validationErrors.propertyName" class="field-error">{{ validationErrors.propertyName }}</p>
            <p v-else class="field-hint">输入地址对应的属性名称</p>
          </div>
        </div>

        <div class="form-row two-columns">
          <div class="form-field">
            <label for="station">所属工位</label>
            <select
                id="station"
                v-model="form.station"
                :disabled="isLoading"
            >
              <option value="">-- 请选择工位 --</option>
              <option value="station1">工位1</option>
              <option value="station2">工位2</option>
            </select>
          </div>

          <div class="form-field">
            <label for="category">地址类别</label>
            <select
                id="category"
                v-model="form.category"
                :disabled="isLoading"
            >
              <option value="">-- 请选择类别 --</option>
              <option value="realtime">实时工艺</option>
            </select>
          </div>
        </div>

        <div class="form-row two-columns">
          <div class="form-field">
            <label for="type">数据类型</label>
            <select
                id="type"
                v-model="form.type"
                :disabled="isLoading"
                @change="handleTypeChange"
            >
              <option value="">-- 请选择数据类型 --</option>
              <option value="int">整数 (Int)</option>
              <option value="float">浮点数 (Float)</option>
            </select>
          </div>

          <div class="form-field" v-if="form.type === 'string'">
            <label for="length">字符串长度</label>
            <input
                type="number"
                id="length"
                v-model.number="form.length"
                class="form-input"
                placeholder="请输入字符串长度"
                min="1"
            />
          </div>
        </div>

        <div class="form-row">
          <div class="form-field">
            <label for="description">描述</label>
            <input
                type="text"
                id="description"
                v-model="form.description"
                placeholder="输入地址用途描述"
                :disabled="isLoading"
            />
          </div>
        </div>

        <div class="form-actions">
          <button
              type="button"
              class="hmi-button hmi-button-secondary"
              @click="cancelEdit"
              :disabled="isLoading"
          >
            取消
          </button>
          <button
              type="submit"
              class="hmi-button hmi-button-primary"
              :disabled="isLoading"
          >
            <i :class="isLoading ? 'fas fa-spinner fa-spin' : 'fas fa-save'"></i>
            {{ isLoading ? '保存中...' : isEditMode ? '保存修改' : '保存地址' }}
          </button>
        </div>
      </form>
    </main>

    <!-- 通知消息 -->
    <div
        v-if="notification.show"
        class="notification"
        :class="{
        'notification-success': notification.type === 'success',
        'notification-error': notification.type === 'error'
      }"
    >
      <span>{{ notification.message }}</span>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted, onBeforeUnmount} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import AppHeader from '@/components/AppHeader.vue';
import plcAddressStore from '@/api/plcAddress';
import {logger} from '@/utils/logger';

const router = useRouter();
const route = useRoute();

// --- 响应式数据 ---
// 表单数据
const form = reactive({
  id: '',
  address: '',
  propertyName: '',
  station: '',
  category: '',
  type: '',
  description: ''
});

// 加载状态
const isLoading = ref(false);

// 表单验证错误
const validationErrors = reactive({
  address: '',
  propertyName: '',
  station: '',
  category: '',
  type: '',
  description: ''
});

// 通知消息状态
const notification = reactive({
  show: false,
  message: '',
  type: 'success', // 'success' 或 'error'
  timeoutId: null
});

// --- 计算属性 ---
// 是否为编辑模式
const isEditMode = computed(() => {
  return !!route.params.id;
});

// 是否有验证错误
const hasValidationErrors = computed(() => {
  return Object.values(validationErrors).some(error => error !== '');
});

// --- 方法 ---
// 加载地址数据 (编辑模式)
const loadAddressData = async () => {
  if (!isEditMode.value) return;

  isLoading.value = true;

  try {
    const addressId = route.params.id;
    const data = await plcAddressStore.getById(addressId);

    if (!data) {
      throw new Error('未找到指定地址');
    }

    Object.assign(form, data);
    logger.info(`已加载PLC地址数据: ${data.address}`);

  } catch (error) {
    logger.error(`加载地址数据失败: ${error.message}`);
    showNotification('加载地址数据失败: ' + (error.message || '未知错误'), 'error');
    setTimeout(() => {
      router.push('/settings/plc-address-config');
    }, 2000);
  } finally {
    isLoading.value = false;
  }
};

// 处理类别变更
const handleCategoryChange = () => {
  // 简化处理，只需要验证表单
  validateForm();
};

// 验证属性名称
const validatePropertyName = () => {
  validationErrors.propertyName = '';

  if (!form.propertyName.trim()) {
    validationErrors.propertyName = '请输入地址属性名称';
    return;
  }

  // 检查属性名称格式，只允许字母、数字、下划线
  const regex = /^[a-zA-Z0-9_]+$/;
  if (!regex.test(form.propertyName)) {
    validationErrors.propertyName = '属性名称只能包含字母、数字和下划线';
    return;
  }
};

// 验证地址格式
const validateAddress = () => {
  // 清除之前的错误
  validationErrors.address = '';

  // 检查是否为空
  if (!form.address.trim()) {
    validationErrors.address = '请输入PLC地址';
    return;
  }

  // 检查格式: M, MW, D, R, Q 开头，后跟数字，可选连续范围
  const regex = /^(M|MW|D|R|Q)[0-9]+(-[0-9]+)?$/;
  if (!regex.test(form.address)) {
    validationErrors.address = '地址格式无效，请使用正确的格式 (M/MW/D/R/Q + 数字)';
    return;
  }
};


// 保存地址
const saveAddress = async () => {
  // 先验证表单
  validateAddress();

  if (validationErrors.address) {
    showNotification('请修正表单中的错误', 'error');
    return;
  }

  isLoading.value = true;
  try {
    const addressData = {
      address: form.address.trim(),
      propertyName: form.propertyName.trim(),
      station: form.station,
      category: form.category,
      type: form.type,
      description: form.description.trim()
    };

    if (isEditMode.value) {
      addressData.id = form.id;
      await plcAddressStore.update(addressData);
      logger.info(`成功更新PLC地址: ${addressData.address}`);
      showNotification('地址更新成功', 'success');
    } else {
      await plcAddressStore.add(addressData);
      logger.info(`成功创建PLC地址: ${addressData.address}`);
      showNotification('地址创建成功', 'success');
    }

    // 延迟返回，让用户看到成功消息
    setTimeout(() => {
      router.back();
    }, 1500);
  } catch (error) {
    logger.error(`保存地址失败: ${error.message}`);
    showNotification('保存地址失败: ' + (error.message || '未知错误'), 'error');
  } finally {
    isLoading.value = false;
  }
};

// 取消编辑
const cancelEdit = () => {
  router.back();
};

// 显示通知
const showNotification = (message, type = 'success') => {
  notification.message = message;
  notification.type = type;
  notification.show = true;

  // 清除之前的定时器
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId);
  }

  // 3秒后自动关闭
  notification.timeoutId = setTimeout(() => {
    notification.show = false;
  }, 3000);
};

// --- 生命周期钩子 ---
onMounted(async () => {
  // 在编辑模式下加载地址数据
  if (isEditMode.value) {
    await loadAddressData();
  }
});

onBeforeUnmount(() => {
  // 清除通知定时器
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId);
  }
});
</script>

<style scoped>
/* --- 主内容区域 --- */
main {
  flex-grow: 1;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  gap: 1rem;
}

/* --- 页面标题 --- */
.page-header {
  margin-bottom: 1rem;
}

.page-title {
  font-size: 1.25rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 0.25rem;
}

.page-description {
  font-size: 0.875rem;
  color: var(--text-tertiary);
}

/* --- 表单样式 --- */
.address-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  background-color: white;
  border: 1px solid var(--border-color);
  border-radius: 0.5rem;
  padding: 1.5rem;
}

.form-row {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.form-row.two-columns {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.form-field {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.form-field label {
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--text-secondary);
}

.required-mark {
  color: var(--status-red);
  margin-left: 0.25rem;
}

.form-field input,
.form-field select {
  width: 100%;
  padding: 0.6rem 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: 0.375rem;
  font-size: 0.875rem;
  background-color: white;
}

.form-field input:focus,
.form-field select:focus {
  outline: none;
  border-color: var(--accent-blue);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.25);
}

.form-field.has-error input,
.form-field.has-error select {
  border-color: var(--status-red);
  background-color: rgba(253, 232, 232, 0.3);
}

.field-error {
  font-size: 0.75rem;
  color: var(--status-red);
  margin-top: 0.25rem;
}

.field-hint {
  font-size: 0.75rem;
  color: var(--text-tertiary);
  margin-top: 0.25rem;
}

/* --- 表单分节 --- */
.form-section {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px dashed var(--border-color);
}

.section-title {
  font-size: 1rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 1rem;
}

/* --- 表单操作区 --- */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
  padding-top: 1.5rem;
  border-top: 1px solid var(--border-color);
}

/* --- 按钮样式 --- */
.hmi-button {
  padding: 0.6rem 1rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.4rem;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  cursor: pointer;
}

.hmi-button i {
  font-size: 0.9em;
}

.hmi-button-primary {
  background-color: var(--accent-blue);
  color: white;
}

.hmi-button-primary:hover {
  background-color: #2563eb;
}

.hmi-button-secondary {
  background-color: white;
  color: var(--text-primary);
  border-color: var(--border-color);
}

.hmi-button-secondary:hover {
  background-color: #f9fafb;
  border-color: #d1d5db;
}

.hmi-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* --- 通知样式 --- */
.notification {
  position: fixed;
  bottom: 1rem;
  left: 50%;
  transform: translateX(-50%);
  padding: 0.75rem 1rem;
  border-radius: 0.375rem;
  color: white;
  font-weight: 500;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  z-index: 100;
  opacity: 0;
  visibility: hidden;
  animation: fadeInOut 3s ease-in-out forwards;
}

.notification-success {
  background-color: var(--status-green);
}

.notification-error {
  background-color: var(--status-red);
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
    visibility: visible;
  }
  10% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    visibility: hidden;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-row.two-columns {
    grid-template-columns: 1fr;
  }
}
</style>
